﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace Catsland.Core
{
    public class TypeManager
    {
        Dictionary<string, Type> m_catcomponent_types;
        public Dictionary<string, Type> CatComponents
        {
            get { return m_catcomponent_types; }
        }

        Dictionary<string, Type> m_invoker_types;
        public Dictionary<string, Type> InvokerTypes
        {
            get { return m_invoker_types; }
        }
        
        // TODO: add more dictionary

        public Type GetCatComponentType(string type_name)
        {
            if (m_catcomponent_types != null)
            {
                return m_catcomponent_types[type_name];
            }
            else
            {
                return null;
            }
        }

        public void AddCatComponentType(string type_name, Type type)
        {
            if (m_catcomponent_types == null)
            {
                m_catcomponent_types = new Dictionary<string, Type>();
            }
            m_catcomponent_types.Add(type_name, type);
        }

        public Type GetInvokerType(string type_name)
        {
            if (m_invoker_types == null)
            {
                return null;
            }
            if (m_invoker_types.ContainsKey(type_name))
            {
                return m_invoker_types[type_name];
            }
            return null;
        }

        public void AddInvokerType(string type_name, Type type)
        {
            if (m_invoker_types == null)
            {
                m_invoker_types = new Dictionary<string, Type>();
            }
            m_invoker_types[type_name] = type;
        }

        public void Load_Plugins(string lib_path)
        {
            m_catcomponent_types = new Dictionary<string, Type>();
            m_invoker_types = new Dictionary<string, Type>();

            string[] files = Directory.GetFiles(lib_path, "*.dll");
            foreach (string file in files)
            {
                Assembly assembly = Assembly.LoadFrom(file);
                Type[] types = assembly.GetTypes();
                Console.WriteLine("Load cat component class from: " + assembly.GetName().Name);
                foreach (Type type in types)
                {
                    Console.WriteLine("- Load class: " + type.Name);

                    if (type.IsSubclassOf(typeof(CatComponent)))
                    {
                        m_catcomponent_types.Add(type.Name, type);
                    }

                    if (type.GetInterface(typeof(TriagerInvoker).Name) != null)
                    {
                        // has implement trigger invoker interface
                        m_invoker_types.Add(type.Name, type);
                    }
                }
            }
        }
    }
}
